package database

import (
	"fmt"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"

	"xian-server/lib/cfg"
	"xian-server/lib/context"
)

type BaseModel struct {
	CreateUsrId    int       `db:"create_usr_id" json:"create_usr_id"`
	CreateUsrIdLbl string    `json:"create_usr_id_lbl"`
	CreateTime     time.Time `db:"create_time" json:"create_time"`
	UpdateUsrId    int       `db:"update_usr_id" json:"update_usr_id"`
	UpdateUsrIdLbl string    `json:"update_usr_id_lbl"`
	UpdateTime     time.Time `db:"update_time" json:"update_time"`
	DeleteUsrId    int       `db:"delete_usr_id" json:"delete_usr_id"`
	DeleteUsrIdLbl string    `json:"delete_usr_id_lbl"`
	DeleteTime     time.Time `db:"delete_time" json:"delete_time"`
}

func Setup() {
	db, err := sqlx.Open(
		cfg.DatabaseSetting.Type,
		fmt.Sprintf(
			"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
			cfg.DatabaseSetting.User,
			cfg.DatabaseSetting.Password,
			cfg.DatabaseSetting.Host,
			cfg.DatabaseSetting.Name))
	if err != nil {
		log.Fatalf("sqlx.Setup err: %v", err)
	}
	db.SetMaxOpenConns(500) // 最大连接数
	db.SetMaxIdleConns(20)  // 最大空闲连接数
	context.DB = db
}
